package xyz.lwm.lazycat.transaction;

import xyz.lwm.lazycat.aop.Aspect;
import xyz.lwm.lazycat.aop.info.MethodInfo;
import xyz.lwm.lazycat.utility.matcher.Matcher;
import xyz.lwm.lazycat.aop.matcher.Matchers;
import xyz.lwm.lazycat.aop.InvocationHandler;
import xyz.lwm.lazycat.transaction.execute.TranDefinition;
import xyz.lwm.lazycat.utility.reflect.AnnotationUtil;
import xyz.lwm.lazycat.utility.reflect.Annotations;

import java.lang.reflect.Method;

/**
 * 事务切面
 *
 * @author lwm
 */
class TransactionAspect implements Aspect {

    @Override
    public Matcher<MethodInfo> matcher() {
        return Matchers.methodAnnotated(Transactional.class);
    }

    @Override
    public InvocationHandler interceptor() {
        return invocation -> {
            Method method = invocation.getMethod();
            Annotations annotations = AnnotationUtil.getAnnotations(method);
            Transactional transactional = annotations.getAnnotation(Transactional.class);
            assert transactional != null;
            TranDefinition tranDefinition = new TranDefinition(transactional.propagation(),
                    transactional.isolation(), transactional.readOnly(), transactional.rollbackFor());
            TransactionUtil.exec(tranDefinition, invocation::invoke);
        };
    }

}
